/**
 * Created by syf on 2015/11/23.
 */
var AV = require("leanengine");
var async = require("async");

var WMProduct = AV.Object.extend("WMProduct");
var Seller = AV.Object.extend("Seller");

module.exports = {
    addProduct: function (data) {
        var promise = new AV.Promise();
        var product = [];
        async.waterfall([
            function (callback) {
                for (var i = 0; i < data.length; i++) {
                    var productItem = new WMProduct();
                    productItem.set("sellerId", data[i].sellerId);
                    productItem.set("pName", data[i].pName);
                    productItem.set("specName", data[i].specName);
                    productItem.set("price", data[i].price);
                    //product.push(productItem);
                    productItem.save().then(function (res) {
                        product.push(res);
                    }).catch(function (err) {
                        callback({code: 9999, reason: err});
                    })
                }
                callback(null, product);
            }], function (err, product) {
            if (err) {
                promise.reject(err);
            } else {
                promise.resolve(product);
            }
        })
        return promise;
    },

    getproductList: function (sellerId, pageIndex, pagesize, searchInfo) {
        var promise = new AV.Promise();
        async.waterfall([
            function (callback) {
                if (sellerId) {
                    //var query = new AV.Query(WMProduct);
                    var skipCount = (pageIndex - 1) * pagesize;
                    var sql = "select * from WMProduct where sellerId='" + sellerId + "' limit " + skipCount + "," + pagesize + " order by createdAt desc";

                    if (searchInfo != "") {
                        sql = "select * from WMProduct where sellerId='" + sellerId + "' and pName like '%" + searchInfo + "%' limit " + skipCount + "," + pagesize + " order by createdAt desc";
                    }
                    AV.Query.doCloudQuery(sql, {
                        success: function (result) {
                            var results = result.results;
                            callback(null, results);
                        }, error: function (err) {
                            callback({code: 9999, reason: err});
                        }
                    })
                }
            }, function (results, callback) {
                var sql = "select count(*) from WMProduct where sellerId='" + sellerId + "'";

                if (searchInfo != "") {
                    sql = "select count(*) from WMProduct where sellerId='" + sellerId + "' and pName like '%" + searchInfo + "%'";
                }
                AV.Query.doCloudQuery(sql, {
                    success: function (result) {
                        var count = result.count;
                        callback(null, results, count);
                    }, error: function (err) {
                        callback({code: 9999, reason: err});
                    }
                })
            }], function (err, results, count) {
            if (err) {
                promise.reject(err);
            } else {
                promise.resolve(results, count);
            }
        })
        return promise;
    },

    getproductListForOrder: function (sellerId) {
        var promise = new AV.Promise();
        async.waterfall([
            function (callback) {
                if (sellerId) {
                    var query = new AV.Query(WMProduct);
                    query.equalTo("sellerId", sellerId);
                    query.equalTo("status", true);
                    query.descending("createdAt");
                    query.find().then(function (result) {
                        callback(null, result);
                    }).catch(function (err) {
                        callback({code: 9999, reason: err});
                    });
                }
            }], function (err, result) {
            if (err) {
                promise.reject(err);
            } else {
                //console.log(result);
                promise.resolve(result);
            }
        })
        return promise;
    },
    getProductById: function (productId) {
        var promise = new AV.Promise();
        var query = new AV.Query(WMProduct);
        query.equalTo("objectId", productId);
        query.find().then(function (res) {
            promise.resolve(res[0]["_serverData"], res[0]["id"]);
        }).catch(function (err) {
            promise.reject(err);
        })
        return promise;
    },

    saveProduct: function (data) {
        var promise = new AV.Promise();
        //for (var i = 0; i < data.length; i++) {
        var price = data[0].price;
        var pName = data[0].pName;
        var specName = data[0].specName;
        var productItem = new WMProduct();
        var query = new AV.Query(WMProduct);
        query.get(data[0].productId).then(function (res) {
            res.set("price", price);
            res.set("specName", specName);
            res.set("pName", pName);
            res.save().then(function (res) {
                promise.resolve(res);
            }).catch(function (err) {
                promise.reject(err);
            });
        })
        return promise;
    },

    upProduct: function (productID) {
        //console.log(productID);
        var promise = new AV.Promise();
        var query = new AV.Query(WMProduct);
        query.get(productID, {
            success: function (res) {
                res.set("status", true);
                res.save();
                promise.resolve(res);
            },
            error: function (err) {
                promise.reject(err);
            }
        })
        return promise;
    },

    downProduct: function (productID) {
        //console.log(productID);
        var promise = new AV.Promise();
        var query = new AV.Query(WMProduct);
        query.get(productID, {
            success: function (res) {
                res.set("status", false);
                res.save();
                promise.resolve(res);
            },
            error: function (err) {
                promise.reject(err);
            }
        })
        return promise;
    },

    getShop: function (userID) {
        var promise = new AV.Promise();
        var query = new AV.Query(Seller);
        query.get(userID).then(function (res) {
            //console.log("123");
            //console.log(res["_hashedJSON"]);
            //console.log(res["branchShop"]);
            //console.log("123");
            //console.log(res["branchShop"]);
            //console.log(res["_hashedJSON"]);   console.log("ds");
            if(res["_serverData"]["branchShop"]!=null){
                promise.resolve(res["_hashedJSON"]);
            }else{
                promise.resolve("");
            }

            //if (res["_hashedJSON"].count !=undefined) {
            //
            //    //console.log();
            //
            //
            //} else {
            //    promise.resolve("");
            //}
        }).catch(function (err) {
            promise.reject(err);
        })
        return promise;
    },

    saveShop: function (userID, branchShop) {
        var promise = new AV.Promise();
        var query = new AV.Query(Seller);
        query.get(userID).then(function (res) {
            //console.log(userID);
            //console.log(res);
            //console.log(branchShop);
            res.set("branchShop", branchShop);
            res.save();
            promise.resolve(res);
        }).catch(function (err) {
            promise.reject(err);
        })
        return promise;
    }
}